package com.example.springtransdemo.controller;

import com.example.springtransdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("trans")
public class TransController {

    @Autowired
    private UserService userService;
    @Transactional
    @RequestMapping("/registry")
    public Boolean registry(String userName,String password){
        Integer result = userService.insertInfo(userName,password);
        log.info("影响的行数:"+result);
        return true;
    }

    @Transactional
    @RequestMapping("/registry2")
    public Boolean registry2(String userName,String password){
        Integer result = userService.insertInfo(userName,password);
        log.info("影响的行数:"+result);
        int i = 10/0;
        return true;
    }

    @Transactional
    @RequestMapping("/registry3")
    public Boolean registry3(String userName,String password){
        Integer result = userService.insertInfo(userName,password);
        log.info("影响的行数:"+result);
        try {
            int i = 10/0;
        }catch (Exception e){
            log.info("出现异常");
        }
        return true;
    }

    @Transactional
    @RequestMapping("/registry4")
    public Boolean registry4(String userName,String password){
        Integer result = userService.insertInfo(userName,password);
        log.info("影响的行数:"+result);
        try {
            int i = 10/0;
        }catch (Exception e){
            log.info("出现异常");
            throw e;
        }
        return true;
    }

    @Transactional
    @RequestMapping("/registry5")
    public Boolean registry5(String userName,String password){
        Integer result = userService.insertInfo(userName,password);
        log.info("影响的行数:"+result);
        try {
            int i = 10/0;
        }catch (Exception e){
            log.info("设置手动回滚");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class,isolation = Isolation.DEFAULT)
    @RequestMapping("/registry6")
    public Boolean registry6(String userName,String password) throws IOException {
        Integer result = userService.insertInfo(userName,password);
        log.info("影响的行数:"+result);
        if(true){
            throw new IOException();
        }
        return true;
    }
}
